/*
 * @(#)SQLLogger.java
 * Project: APEP-JZCG 
 *
 * Modify Information:
 * =============================================================================
 *   Author       Date       Description
 *   ------------ ---------- ---------------------------------------------------
 *   john        2008-08-08  First release
 *
 * Copyright Notice:
 * =============================================================================
 *    Copyright (c) 2001-2007 Auto-Parts E-Procurement Co., Ltd. 
 *        No.251-1 Wuning Road, Shanghai, 200063, China All rights reserved.
 *
 *    This software is the confidential and proprietary information of
 *        Auto-Parts E-Procurement Co., Ltd. ("Confidential Information").
 *        You shall not disclose such Confidential Information and shall use it
 *        only in accordance with the terms of the license agreement you entered
 *        into with APEP.
 *
 * Warning:
 * =============================================================================
 *   
 * 
 */
package com.hitrust.gs.lib;

import org.apache.log4j.*;
import com.hitrust.gs.lib.db.*;

public class SQLLogger
{
	private static Logger mLog = Logger.getLogger("sqllogger");
	
	private static String mNeed = GSSystemConfigurator.getParam("gs.SQLLog");
	
	public static void log(String info) 
	{
		if(mNeed==null||!mNeed.equalsIgnoreCase("true")) return ;
		if(info==null||info.equalsIgnoreCase("Success")) return ;
		try
		{
			mLog.info(info);	
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
	
	public static String replaceFirst(String orgStr, String oldString, String newString) throws Exception
	{
		if (orgStr == null) {
			return null;
		}
		StringBuffer output = new StringBuffer();
		int lengOfsource = orgStr.length();
		int lengOfold = oldString.length();
		int posStart = 0;
		int pos;
		if((pos = orgStr.indexOf(oldString, posStart)) >= 0)
		{
			output.append(orgStr.substring(posStart, pos));
			output.append(newString);
			posStart = pos + lengOfold;
		}
		if (posStart < lengOfsource) {
			output.append(orgStr.substring(posStart));
		}
		return output.toString();
	 
	}
	
	
	public static void log(String sql,Object[] params)
	{
		try
		{
		    String ret = replaceFirst(sql, "", "") ;
			for(int i=0;params!=null && i<params.length;i++)
			{
				Object p =  params[i];
				
				if(p instanceof String)
				{
					ret = replaceFirst(ret, "?", "'"+p+"'");
				}
				else if(p instanceof Integer)
				{
				    int v=((Integer)p).intValue();
					ret = replaceFirst(ret, "?", ""+v);
				}
				else if(p instanceof Double)
				{
				    double v = ((Double)p).doubleValue();
					ret = replaceFirst(ret, "?", ""+v);
				}
				else if(p instanceof GSNullSQLType)
				{
					ret = replaceFirst(ret, "?", "null");
				}
				else
				{
					
				}
			}
			log(ret);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}
